package api

import (
	"admin100/app/model"
	"admin100/app/model/commonmodel/userEnum"
	"admin100/app/service"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"admin100/library/define/defLang"
	"admin100/library/response"
	"admin100/library/utils"

	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
)

var Login = &loginApi{}

type loginApi struct {
}

// @summary 用户登录
// @tags    登录管理
// @produce json
// @param   account formData  string true "帐户名"
// @param   password formData  string true "密码"
// @router  /login [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *loginApi) Login(r *ghttp.Request) {
	var (
		req *model.MyadminUserLoginReq
		now = int(gtime.Timestamp())
	)
	if err := r.ParseForm(&req); err != nil {
		response.JsonExitWithMsg(r, define.Fail, err.Error())
	}

	//获取用户
	user := service.User.FetchUserByAccount(req.Account)
	password := utils.Md5Direct(req.Password)

	if user.CanLoginTime > now {
		errText := gconv.String(user.ContinueLoginErrorTimes) + "次密码连续出错" +
			", " + gconv.String(user.CanLoginTime-now) + "秒后可尝试再次登录"
		response.JsonExitWithMsg(r, define.Fail, errText)
	}

	if user.Password != password {
		service.User.SetCanLogTimes(user)
		defErr.Panic(define.PwdErr)
	}

	if user.Status != userEnum.Enabled {
		defErr.Panic(define.UserForbidden)
	}

	service.User.SetSomeFieldsAfterLogin(r.GetClientIp(), user)

	service.Context.Set(r.Context(), user)
	service.Session.SetUser(r.Context(), user)
	response.JsonExitWithMsg(r, define.Success, defLang.GotMsg(define.LoginSuccess))
}

// @summary 用户退出
// @tags    登录管理
// @produce json
// @router  /logout [GET]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *loginApi) Logout(r *ghttp.Request) {
	service.Session.DelUser(r.Context())
	response.JsonSuc(r)
}
